package com.parking.carsystem.parkingchargesystem.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.parking.carsystem.parkingchargesystem.R;
import com.parking.carsystem.parkingchargesystem.adapter.HomeCustomPagerAdapter;
import com.parking.carsystem.parkingchargesystem.common.Constant;
import com.parking.carsystem.parkingchargesystem.fragment.FragmentFactory;
import com.parking.carsystem.parkingchargesystem.fragment.HomeFragment;
import com.parking.carsystem.parkingchargesystem.fragment.UserFragment;
import com.parking.carsystem.parkingchargesystem.module.UserInfoModel;
import com.parking.carsystem.parkingchargesystem.utils.SPUtils;
import com.parking.carsystem.parkingchargesystem.utils.Utils;
import com.parking.carsystem.parkingchargesystem.view.NoScrollViewPager;
import com.parking.carsystem.parkingchargesystem.view.TopImageTextView;
import com.parking.carsystem.parkingchargesystem.view.cutimage.Crop;

import java.io.File;

import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.internal.Util;

public class MainActivity extends BaseActivity implements View.OnClickListener {


    @BindView(R.id.back)
    ImageView back;
    @BindView(R.id.setting)
    TextView setting;
    @BindView(R.id.text)
    TextView text;
    @BindView(R.id.title_bg)
    RelativeLayout titleBg;
    @BindView(R.id.viewpage)
    NoScrollViewPager viewpage;
    @BindView(R.id.bottom_home)
    TopImageTextView bottomHome;
    @BindView(R.id.bottom_commity)
    TopImageTextView bottomCommity;
    @BindView(R.id.bottom)
    LinearLayout bottom;
    private long lastMillions;
    private HomeCustomPagerAdapter pagerAdapter;
    private HomeFragment fragment;
    private UserFragment userFragment;
    TextView[] textViews;
    private UserInfoModel tempUserInfoModel;

    @Override
    protected int getContentViewId() {
        return R.layout.activity_main;
    }


    @Override
    public void initView() {
        //根据状态栏颜色来决定状态栏文字用黑色还是白色
        Utils.setStatusBarMode(this, false, R.color.color_2c78ac);
        back.setVisibility(View.GONE);
        setTitleColor();
        requestPermission();
        textViews = new TextView[]{bottomHome, bottomCommity};
        textViews[0].setSelected(true);
        bottomHome.setOnClickListener(this);
        bottomCommity.setOnClickListener(this);
        getUserInfo();
    }

    @Override
    public void initData() {
        text.setText("国联智慧停车");
        pagerAdapter = new HomeCustomPagerAdapter(getSupportFragmentManager());
        viewpage.setAdapter(pagerAdapter);
        fragment = (HomeFragment) FragmentFactory.getCustumFragmentInsance(0);
        userFragment = (UserFragment) FragmentFactory.getCustumFragmentInsance(1);
        viewpage.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                setTitleColor();
                if (position == 0) {
                    text.setText("国联智慧停车");
                }else {
                    text.setText("个人中心");
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

    private void setTitleColor() {
        text.setTextColor(getResources().getColor(R.color.white));
        titleBg.setBackgroundResource(R.mipmap.head_background);
//        titleBg.setBackgroundColor(getResources().getColor(R.color.white));
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK) {
            long currentMillions = System.currentTimeMillis();
            long delta = currentMillions - lastMillions;
            lastMillions = currentMillions;
            if (delta < 2000) {
                // 登出操作
//                System.exit(0);
                return super.onKeyDown(keyCode, event);
            }
            showToast("再按一次退出应用程序");
            return true;
        }

        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.bottom_home:
                changFragment(0);
                break;
            case R.id.bottom_commity:
                changFragment(1);
                break;
        }
    }


    private void changFragment(int item) {
        for (int i = 0; i < textViews.length; i++) {
            if (item == i) {
                textViews[i].setSelected(true);
                textViews[i].setTextColor(getResources().getColor(R.color.colorPrimary));
            } else {
                textViews[i].setSelected(false);
                textViews[i].setTextColor(getResources().getColor(R.color.login_able_bg));
            }
        }
        viewpage.setCurrentItem(item);
    }

    @Override
    public void updateData(UserInfoModel userInfoModel) {
        tempUserInfoModel = userInfoModel;
        if (tempUserInfoModel !=null && tempUserInfoModel.data != null) {
            SPUtils.getInstance(MainActivity.this).put(Constant.USER_ID, tempUserInfoModel.data.id);
            userFragment.updateView();
        }
    }

    public UserInfoModel getUserMessage() {
        return tempUserInfoModel;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        if (requestCode == Constant.ADDPARKINGRESULTCODE) {
            fragment.getGroupList("");
            return;
        }
        switch (requestCode) {
            case Constant.REQUEST_CODE_OPEN_CAMERA:
                if (resultCode == RESULT_OK) {
                    String takePhotoPath = mPhotoFile.getAbsolutePath();
                    final File file = new File(takePhotoPath);
                    sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(file)));
//                    updateImage(takePhotoPath);
//                    Uri uriFromPath = Utils.getMediaUriFromPath(this, takePhotoPath);
                    beginCrop(Uri.fromFile(file));
                }
                break;
            case Constant.REQ_CODE_GALLERY_FACE:
//                String imagepath = Utils.chooseImage(requestCode, data, this);
//                updateImage(imagepath);
                Uri uri = Utils.chooseImageUri(requestCode, data, this);
                beginCrop(uri);
                break;
            case Crop.REQUEST_CROP:
                if (resultCode == RESULT_OK) {
                    if (data != null) {
                        Uri output = Crop.getOutput(data);
                        sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, output));
                        String  path = Utils.getRealPathFromUri(this, output);
                        updateImage(path);
                    }
                }
                break;
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    private void updateImage(String takePhotoPath) {
        userFragment.getPhotoFile(takePhotoPath);
    }
    private void beginCrop(Uri source) {
        Uri destination = Uri.fromFile(new File(getCacheDir(), String.valueOf(System.currentTimeMillis())+".jpg"));
        Crop.of(source, destination).asSquare().start(this);
    }
}
